<?php
//import database config
include_once(dirname(__FILE__).'/../Conf/DataBase.php');
include_once(dirname(__FILE__).'/../Conf/Inc.php');
//no error report
error_reporting(E_ALL ^ E_DEPRECATED);

//use a class for database operation
class DBHelper{
	//define a variable for connection
	static private $conn;

	//single model
	static private $_instance;

	static public function getInstance()
	{
		if(!(self::$_instance instanceof self))
		{
			self::$_instance = new self();
		}
		return self::$_instance;
	}

	//default construction
	private function __construct()
	{
		if(!self::$conn)
		{
			$this->connect(mysql_server_name,mysql_username,mysql_password,mysql_database,mysql_code);
		}
	}

	//do connect mysql database
	function connect($server_name,$mysql_user,$mysql_pwd,$database_name,$code)
	{
		//begin connect
		self::$conn = mysql_connect($server_name,$mysql_user,$mysql_pwd) or die(mysql_error()) ; 
		//set data code
		mysql_query('set names '.$code); 
		//choose database
		mysql_select_db($database_name); 
	}	

	/*
	* @todo	get a row
	* @return 	an array[] or false
	*/
	function getRow($sql)
	{
		//ensure already in connection
		if(!self::$conn)
		{
			die();
		}
		//1.do query
		$result = mysql_query($sql,self::$conn); 
		//2.return array[]
		return mysql_fetch_assoc($result);
	}

	/*
	* @todo	get  rows
	* @return 	an array[][] or false
	*/
	function getRows($sql)
	{
		//ensure already in connection
		if(!self::$conn)
		{
			die();
		}
		//1.do query
		$result = mysql_query($sql,self::$conn); 
		//2.define a array[]
		$rows = array();
		//3.fill $rows
		while($row = mysql_fetch_assoc($result))
		{
			array_push($rows, $row);
		}
		return $rows;
	}

	/*
	* @todo	inser or delete or update
	* @return 	true or false
	*/
	function doQuery($sql)
	{
		//ensure already in connection
		if(!self::$conn)
		{
			die();
		}
		//1.do query
		$result = mysql_query($sql,self::$conn); 
		//2.return true?false
		return !$result?false:true;
	}

	/*
	*@todo 	get last insert data id
	*@return 	id
	*/
	function getLastInsertId()
	{
		//ensure already in connection
		if(!self::$conn)
		{
			die();
		}
		//return the last insert data 's 'id
		return mysql_insert_id();
	}

	//default destruction
	function __destruct()
	{
		mysql_close();
	}
}
?>